import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'
import storage from 'store'
import { APP_USER, APP_DEPT } from '@/store/mutation-types'
import { previewDocByDocName, savePreviewDocByMaterial, savePreviewDocPdfByDocName } from '@/api/accept/business_Approve'
import { renderAsync } from 'docx-preview'
import { initPreviewDocParam } from '@/api/accept/business_Approve'
import moment from 'moment'
import { getSetting, getDecisionSetting } from '@/views/handleCase/base/formSetting'
import { startBusinessProced } from '@/api/accept/business_Approve'
import { Tp_accept,Tp_hear,Tp_execute, Tp_proctypeEnum } from '@/enumeration/Tp_proctype'
import { Tp_decision } from '@/enumeration/Tp_decision'
import { Tp_procmaterialList } from '@/enumeration/Tp_procmaterial'
import { getAllMaterialByApplyId } from '@/api/accept/aprv_process_materials'

export const BaseCaseHandleMinxin = {
  props: {
    applyid: {
      type: String,
      required: true
    },
    fileItem: {
      type: Array,
      required: true
    },
    busiType: {
      // 业务环节
      type: Number,
      required: true
    },
    processinstanceid: {
      type: String,
      required: false
    },
    decisionType: {
      // 决定类型
      type: Number,
      required: false
    }
  },
  data () {
    return {
      current: 0,
      steps: [],
      labelCol: { span: 4 }, // label宽
      wrapperCol: { span: 20 }, // 组件
      currentUser: storage.get(APP_USER), // 登录人信息
      currentDept: storage.get(APP_DEPT), // 登录人部门
      loading: false, // 按钮显示
      spinning: false, // 加载中
      isResize: false,
      previewFileSrc: '',
      previewLoading: false,
      modalVisible: false,
      cloneFormData: {}, // 初次保存的表单数据
      formSetting: [], // 定义的表单配置
      modalTitle: '', // 标题名称
      currentFormSetting: {}, // 当前的表单配置
      infoForm: {}, // 表单
      rules: {}, // 规则

      allMaterials: [], // 全部对应的材料
      stepSaveData: {}, // 步骤保存的数据
      typeEnum: {} // 对应类型

    }
  },
  components: {
    Splitpanes,
    Pane
  },
  async created () {
    this.infoForm.applyid = this.applyid
    this.current = 0
    this.formSetting = getSetting(this.busiType)
    // this.steps = this.fileItem.filter(element => element.required)
    this.typeEnum = {}
    for (const key in Tp_proctypeEnum) {
      if (Tp_proctypeEnum[key].value === this.busiType) {
        this.typeEnum = Tp_proctypeEnum[key]
      }
    }
    this.queryAllMaterial()
    this.steps = []
    if (this.formSetting && this.formSetting.length > 0) {
      for (const setting of this.formSetting) {
        for (const file of this.fileItem) {
          if (setting.materialType == file.fileType) {
            this.steps.push(file)
          }
        }
      }
    }
  },
  methods: {
    init () {
      this.modalVisible = true
      this.spinning = true
      // 加载当前的数据
      // 决定阶段 特殊处理
      if (this.busiType == Tp_proctypeEnum.hear_decision.value) {
        this.current = 0
        this.formSetting = getDecisionSetting(this.decisionType)
        // this.steps = this.fileItem.filter(element => element.required)
        this.steps = []
        if (this.formSetting && this.formSetting.length > 0) {
          for (const setting of this.formSetting) {
            for (const file of this.fileItem) {
              if (setting.materialType == file.fileType) {
                this.steps.push(file)
              }
            }
          }
        }
      }
      this.initFormAndRule()
      this.$nextTick(() => {
        this.resetForm()
        this.firstLoad()
      })
    },
    async initFormAndRule () {
      this.infoForm = {} // 表单
      this.rules = {} // 规则
      // 构建当前的infoForm字段
      if (this.formSetting && this.formSetting.length > 0) {
        this.currentFormSetting = this.formSetting[this.current]
      }
      if (this.currentFormSetting && this.currentFormSetting.formItem && this.currentFormSetting.formItem.length > 0) {
        try {
          for (const formItem of this.currentFormSetting.formItem) {
            this.$set(this.infoForm, formItem.key, formItem.default)
          }
          for (const rule in this.currentFormSetting.rules) {
            this.$set(this.rules, rule, this.currentFormSetting.rules[rule])
          }
          this.modalTitle = this.currentFormSetting.modalTitle
          // 设置对应的接口查询的值
          for (const formItem of this.currentFormSetting.formItem) {
            if (formItem.type == 'select' && formItem.sourceDataApi != undefined) {
              const apiFunction = formItem.sourceDataApi
              const res = await apiFunction({ applyid: this.applyid })
              console.log('api数据:', res.data)
              if (res.code !== 0) {
                  this.$message.error('获取数据失败')
              } else {
                formItem.sourceData = res.data
              }
            }
          }
        } catch (error) {
          console.error(error)
          this.$message.error('配置加载错误')
        } finally {
          this.spinning = false
        }
      } else {
        this.spinning = false
        this.$message.error('当前查询表单配置错误')
        this.modalVisible = false
      }
    },
    handleCancel () {
      this.resetForm()
      this.$emit('reload')
      this.$emit('close')
      this.modalVisible = false
    },
    resetForm () {
      this.$nextTick(() => {
        if (this.$refs.formComponentRef) {
          this.$refs.formComponentRef.resetFields()
        }
      })
    },
    /**
     * 换行替换
     */
    trimLine (str) {
      return str ? str.replace(/(\r\n|\n|\r)/gm, '').replace(/^\s*|\s*$/g, '') : ''
    },
    resize () {
      this.isResize = true
    },
    resized () {
      this.isResize = false
    },
    getUser () {
      return this.currentUser
    },

    /**
     * 查询全部的材料
     */
    async queryAllMaterial () {
      const res = await getAllMaterialByApplyId({ applyid: this.applyid })
      if (res.code === 0) {
        this.allMaterials = res.data
      } else {
        console.log('查询全部的材料失败', res)
      }
    },
    // 校验当前的页面的文件是否存在
    async validateMaterial () {
      await this.queryAllMaterial()
      if (!this.allMaterials || this.allMaterials.length == 0) {
        return false
      } else {
        // 判断当前的类型是否有文件
        let materialType
        if (this.steps && this.steps.length > 0) {
          if (this.steps.length == 1) {
            const fileItem = this.steps[0]
            if (fileItem) {
              materialType = fileItem.fileType
            }
          } else {
            const fileItem = this.steps[this.current]
            if (fileItem) {
              materialType = fileItem.fileType
            }
          }
        }
        // 判断是否存在文件
        return this.allMaterials.some(element => element.mattype == materialType)
      }
    },
    // 校验当前全部的文件是否存在
    validateAllMaterial () {
      if (!this.allMaterials || this.allMaterials.length == 0) {
        return false
      } else {
        // 判断当前的类型是否有文件
        const materialTypes = []
        if (this.steps && this.steps.length > 0) {
          for (const step of this.steps) {
            materialTypes.push(step.fileType)
          }
        }
        // 判断是否都存在文件
        let allFile = true
        if (materialTypes && materialTypes.length > 0) {
          for (const materialType of materialTypes) {
            if (!this.allMaterials.some(element => element.mattype == materialType)) {
              allFile = false
              break
            }
          }
        }
        return allFile
      }
    },
    /**
     * 初次加载， 将表单数据保存至对应的参数中
     */
    firstLoad () {
      const params = this.initDocParams()
      initPreviewDocParam(this.applyid, params.materilaType).then(res => {
        if (res.code !== 0) {
          console.log('获取初始化表单数据失败')
        } else {
          console.log('获取初始化表单数据成功', res.data)
          if (res.data) {
            for (const key in this.infoForm) {
              if (res.data[key]) {
                this.infoForm[key] = res.data[key]
              }
            }
            // 深度clone
            this.cloneFormData = JSON.parse(JSON.stringify(this.infoForm))
            if (!this.stepSaveData[params.materilaType]) {
              this.stepSaveData[params.materilaType] = this.cloneFormData
            }
          }
        }
        this.loading = false
        params.docfield = JSON.parse(JSON.stringify(this.infoForm))
        this.$nextTick(() => {
          this.sendPreviewDocByDocName(params)
        })
      })
    },

    // 初始化对应的参数
    initDocParams () {
      const params = {
        applyid: this.applyid, // applyid
        materilaType: null,
        docfield: null
      }
      if (this.steps && this.steps.length > 0) {
        if (this.steps.length == 1) {
          const fileItem = this.steps[0]
          if (fileItem) {
            params.materilaType = fileItem.fileType
          }
        } else {
          const fileItem = this.steps[this.current]
          if (fileItem) {
            params.materilaType = fileItem.fileType
          }
        }
      }
      const docfield = JSON.parse(JSON.stringify(this.infoForm))
      // 时间字段进行格式化
      if (this.currentFormSetting && this.currentFormSetting.formItem && this.currentFormSetting.formItem.length > 0) {
        for (const formItem of this.currentFormSetting.formItem) {
          if (formItem.type == 'date') {
            if (this.infoForm[formItem.key]) {
              const formateDate = this.$moment(this.infoForm[formItem.key]).format(formItem.format)
              docfield[formItem.key] = formateDate
            }
          }
        }
      }
      params.docfield = docfield
      console.log('入参参数：' + params)
      return params
    },

    /**
     * 表单focus标红部分
     * @returns
     */
    focusRed () {
      this.loading = false
      // 加延时器的目的是为了vue实例更新未完成，我们可能获取DOM失败的问题
      // 利用原生js的方式，获取所有失败的类名，获得一个数组，取第一个元素获取焦点
      setTimeout(() => {
        const isError = document.getElementsByClassName('has-error')
        const input = isError[0].querySelector('input')
        // console.log(input)
        if (input !== null && input !== 'undefind' && input !== '') {
          isError[0].querySelector('input').focus()
            ? isError[0].querySelector('input').focus()
            : isError[0].querySelector('input').click()
        } else {
          isError[0].querySelector('textarea').focus()
        }
      }, 10)
      return false
    },

    sendPreviewDocByDocName (params) {
      this.previewLoading = true
      previewDocByDocName(this.applyid, params.materilaType, params.docfield).then(res => {
        this.previewLoading = false
        renderAsync(res, this.$refs.file, null, {
          className: 'text-docx', // class name/prefix for default and document style classes
          inWrapper: true, // enables rendering of wrapper around document content
          ignoreWidth: false, // disables rendering width of page
          ignoreHeight: false, // disables rendering height of page
          ignoreFonts: false, // disables fonts rendering
          breakPages: true, // enables page breaking on page breaks
          ignoreLastRenderedPageBreak: true, // disables page breaking on lastRenderedPageBreak elements
          experimental: true, // enables experimental features (tab stops calculation)
          trimXmlDeclaration: true, // if true, xml declaration will be removed from xml documents before parsing
          useBase64URL: false, // if true, images, fonts, etc. will be converted to base 64 URL, otherwise URL.createObjectURL is used
          useMathMLPolyfill: true, // includes MathML polyfills for chrome, edge, etc.
          debug: false // enables additional logging
        }) // 渲染到页面
      })
    },

    // 下载材料
    download () {
      const params = this.initDocParams()
      this.previewLoading = true
      const materialName = Tp_procmaterialList.filter(element => element.value == params.materilaType)[0].name
      // 查找对应的文件名
      savePreviewDocPdfByDocName(this.applyid, params.materilaType, params.docfield)
        .then((res) => {
          // const blob = new Blob([res],{type : "application/vnd.openxmlformats-officedocument.wordprocessingml.document"})
          const blob = new Blob([res], { type: 'application/pdf' })
          var url = window.URL.createObjectURL(blob)
          var a = document.createElement('a')
          a.href = url
          a.download = materialName
          a.click()
        }).finally(() => {
          this.previewLoading = false
      })
    },

    /**
     * 保存当前的文件
     *
     */
    saveDoc () {
      this.$refs.formComponentRef.validate(valid => {
        this.loading = true
        if (valid) {
          console.log('submit!', this.infoForm)
          const params = this.initDocParams()
          savePreviewDocByMaterial(
            this.applyid,
            params.materilaType,
            this.busiType,
            this.getUser().userId,
            this.getUser().fullname,
            params.docfield
          ).then(res => {
            if (res.code !== 0) {
              this.$message.error('保存失败')
            } else {
              this.$message.success('保存成功')
              // 重新查询文件
              this.queryAllMaterial()
              this.stepSaveData[params.materilaType] = this.infoForm
            }
          }).finally(() => {
            this.loading = false
          })
        } else {
          this.focusRed()
        }
      })
    },
    /**
     * 启动流程
     * @param {} res  只在延期的时候传入
     */
    startProcess (res) {
      let content = '行政复议-' + this.typeEnum.name + '审批'
      if (this.busiType == Tp_proctypeEnum.hear_decision.value) {
        content = '行政复议-决定' + Tp_decision[this.decisionType].name + '审批'
      }
      const busiName = this.typeEnum ? this.typeEnum.key : ''
      // 启动流程
      const flowParams = {
        applyid: this.applyid, // applyid
        proctype: busiName, // 操作分类
        userid: this.currentUser.userId,
        username: this.currentUser.fullname,
        processinstanceid: this.processinstanceid, // 流程实例id
        cause: '', // 案由
        describe: '行政复议-' + this.typeEnum.name + '审批' // 行政复议申请
      }
      const docfield = {
      }
      // 延期
      if (this.busiType == Tp_proctypeEnum.hear_delay.value) {
        docfield.daySize = this.infoForm.daySize // 延期天数
      }
      // 决定阶段
      if (this.busiType == Tp_proctypeEnum.hear_decision.value) {
        docfield.decisiontype = this.decisionType // 决定类型
      }
      console.log('流程入参', flowParams)
      this.loading = true
      startBusinessProced(flowParams, docfield).then((res) => {
        if (res.code !== 0) {
          this.$message.error('操作失败')
        } else {
          this.$message.success('操作成功')
          this.$emit('reload')
          this.$emit('close')
          this.modalVisible = false
          // 暂时隐藏流程跳转
          this.$emit('gotoSonRouter', res.data, busiName)
        }
        this.loading = false
      })
    },
    /**
     * 提交表单
     *
     */
    onSubmit () {
      // 如果当前是延期类型的话
      // 查询当前的类型是否存在文件
      //  20240229 去除材料项的必须材料的校验，直接提醒是否启动流程
      let content = '是否发起行政复议-' + this.typeEnum.name + '审批'
      if (this.busiType == Tp_proctypeEnum.hear_decision.value) {
        content = '是否发起行政复议-决定' + Tp_decision[this.decisionType].name + '审批'
      }
      this.$confirm({
        title: '提醒',
        content: content,
        okText: '是',
        cancelText: '否',
        onOk: () => {
          this.startProcess()
        }
      })
    },

    /**
     * 是否传参展示
     * @param {}  是否强制不读取参数
     */
    previewDocByDocName () {
      const params = this.initDocParams()
      this.sendPreviewDocByDocName(params)
    },

    prev () {
      if (this.current > 0) {
        this.current--
        this.initFormAndRule()
        const fileItem = this.steps[this.current]
        const materialType = fileItem.fileType
        // 重置表格
        this.$nextTick(() => {
          this.$refs.formComponentRef.resetFields()
          if (this.stepSaveData[materialType]) {
              this.infoForm = this.stepSaveData[materialType]
              this.previewDocByDocName()
          } else {
            this.firstLoad()
          }
        })
      }
    },

    next () {
      // 校验当前页文件是否存在
      if (this.validateMaterial()) {
        this.current++
        this.initFormAndRule()
        // 重置表格
        this.$nextTick(() => {
          this.$refs.formComponentRef.resetFields()
          this.firstLoad()
        })
      } else {
        this.$confirm({
          title: '提醒',
          content: '当前材料项未上传文件，是否继续',
          okText: '是',
          cancelText: '否',
          onOk: () => {
            this.current++
            this.initFormAndRule()
            // 重置表格
            this.$nextTick(() => {
              this.$refs.formComponentRef.resetFields()
              this.firstLoad()
            })
          }
        })
      }
    }
  }
}
